<?php

namespace App\Http\Controllers\Admin;

use App\Models\User;
use App\Models\UserGroup;
use App\Models\UserRelation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UserController extends BaseController
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function index(){
        $this->assign([
            'uid'=>'',
            'username'=>'',
            'mobile'=>'',
            'email'=>'',
            'time_begin'=>'',
            'time_end'=>'',
            'gid'=>''
        ]);

        $queryParams = [];
        $query = User::with(['group','wallet']);
        $uid = $this->request->input('uid');
        if ($uid) {
            $queryParams['uid'] = $uid;
            $query = $query->where('uid', $uid);
        }

        $username = $this->request->input('username');
        if ($username) {
            $queryParams['username'] = $username;
            $query = $query->where('username', 'LIKE', "%$username%");
        }

        $mobile = $this->request->input('mobile');
        if ($mobile) {
            $queryParams['mobile'] = $mobile;
            $query = $query->where('mobile', $mobile);
        }

        $email = $this->request->input('email');
        if ($email) {
            $queryParams['email'] = $email;
            $query = $query->where('email', $email);
        }

        $time_begin = $this->request->input('time_begin');
        if ($time_begin) {
            $queryParams['time_begin'] = $time_begin;
            $query = $query->where('created_at', '>', strtotime($time_begin));
        }

        $time_end = $this->request->input('time_end');
        if ($time_begin) {
            $queryParams['time_end'] = $time_end;
            $query = $query->where('created_at', '<', strtotime($time_end));
        }

        $gid = $this->request->input('gid');
        if ($gid) {
            $queryParams['gid'] = $gid;
            $query = $query->where('gid', $gid);
        }

        $this->assign($queryParams);
        $users = $query->orderByDesc('uid')->paginate(20);
        $this->assign([
            'users'=>$users,
            'pagination'=>$users->appends($queryParams)->render(),
            'user_status'=>trans('user.user_status'),
            'userGroups'=>UserGroup::userGroups()->orderBy('creditslower')->orderBy('gid')->get(),
        ]);

        return $this->view('admin.user.list');
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delete(Request $request)
    {
        $users = $request->input('users');
        if ($users)
        {
            User::whereIn('uid', $users)->get()->map(function ($user){
                if ($user->uid != 1000000)
                {
                    $user->delete();
                }
            });
        }
        return ajaxReturn();
    }

    public function updateStatus(Request $request)
    {
        $users = $request->input('users');
        if ($users)
        {
            $status = $request->input('status');
            User::whereIn('uid', $users)->update(['status'=>$status]);
        }

        return ajaxReturn();
    }

    public function edit(Request $request){

        $uid = $request->input('uid');
        $user = User::find($uid);
        $userGroups = UserGroup::userGroups()->orderBy('creditslower')->orderBy('gid')->get();
        $systemGroups = UserGroup::systemGroups()->orderBy('gid')->get();

        return $this->view('admin.user.edit', compact('uid','user', 'userGroups', 'systemGroups'));
    }

    public function save(Request $request)
    {
        $uid    = $request->input('uid');
        $mobile = $request->input('mobile');
        $email  = $request->input('email');

        $rules = [];
        $user = User::find($uid);
        if ($mobile){
            if ($mobile != $user->mobile)
            {
                $rules['mobile'] = 'bail|mobile|unique:user';
                $user->mobile = $mobile;
            }
        }

        if ($email){
            if ($email != $user->email)
            {
                $rules['email'] = 'bail|email|unique:user';
                $user->email = $email;
            }
        }

        $password = $request->input('password');
        if ($password)
        {
            $rules['password'] = 'bail|password';
            $user->password = Hash::make($password);
        }

        $validate = Validator::make($request->all(), $rules);

        if ($validate->fails()) {
            foreach ($validate->getMessageBag()->messages() as $messages)
            {
                foreach ($messages as $message)
                {
                    return $this->messager()->error()->message($message)->render();
                }
            }
        }

        $user->gid = $request->input('gid');
        $user->admincp = $request->input('admincp');
        $user->admingid = $request->input('admingid') ? $request->input('admingid') : 0;
        $user->status = $request->input('status');

        $user->save();
        return $this->messager()->message(trans('sysmessage.info update success'))->render();
    }

    public function relation(Request $request)
    {
        $items = UserRelation::with(['user','upuser'])->orderByDesc('created_at')->paginate(20);
        return $this->view('admin.user.relation', [
            'items'=>$items,
            'pagination'=>$items->render()
        ]);
    }

    public function delRelation(Request $request)
    {
        $delete = $request->input('delete');
        if ($delete)
        {
            foreach ($delete as $uid)
            {
                UserRelation::where('uid', $uid)->delete();
            }
        }


        return ajaxReturn();
    }
}
